package com.engine4cloud.tdf.admin.controller;

import com.engine4cloud.tdf.admin.api.dto.SysFileDownloadRequestDTO;
import com.engine4cloud.tdf.admin.api.dto.SysFileUploadRequestDTO;
import com.engine4cloud.tdf.admin.api.dto.SysFileUploadResultDTO;
import com.engine4cloud.tdf.admin.service.SysFileService;
import com.engine4cloud.tdf.common.core.util.R;
import com.engine4cloud.tdf.common.security.annotation.Inner;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件管理
 *
 * @author Luckly
 * @date 2019-06-18 17:18:42
 */
@RestController
@AllArgsConstructor
@RequestMapping("/sys-file")
@Tag(description = "sys-file", name = "文件管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class SysFileController {

	private final SysFileService sysFileService;

	/**
	 * 上传文件 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常
	 *
	 * @param file 资源
	 * @return R(/ admin / bucketName / filename)
	 */
	@Operation(summary = "上传", description = "上传")
	@PostMapping(value = "/upload")
	public R<SysFileUploadResultDTO> upload(@RequestPart("file") MultipartFile file, @Valid @ParameterObject SysFileUploadRequestDTO dto) {
		return R.ok(sysFileService.uploadFile(file, dto));
	}

	@Inner(value = false)
	@Operation(summary = "上传", description = "上传")
	@PostMapping(value = "/uploads", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	public R<SysFileUploadResultDTO> uploads(@RequestPart("file") MultipartFile file, @RequestPart("dto") SysFileUploadRequestDTO dto) {
		return R.ok(sysFileService.uploadFile(file, dto));
	}

	/**
	 * 获取文件返回视图
	 *
	 * @param dto      文件空间/名称
	 * @param response response
	 */
	@Inner(value = false)
	@Operation(summary = "下载", description = "下载")
	@GetMapping("/oss/file")
	public void file(@Valid @ParameterObject SysFileDownloadRequestDTO dto, HttpServletResponse response) {
		sysFileService.getFile(dto, response);
	}

	/**
	 * 获取文件
	 *
	 * @return R<byte [ ]>
	 */
	@Inner(value = false)
	@Operation(summary = "获取文件流字节数组", description = "获取文件流字节数组")
	@PostMapping("/oss/file/byte")
	public R<byte[]> fileBytes(@Valid @RequestBody SysFileDownloadRequestDTO dto) {
		return R.ok(sysFileService.getFile(dto));
	}
}
